<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!-- 加载 React-->
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <!-- 引入 babel-->
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <title>Addition</title>
</head>
<style>
    #app {
        text-align: center;
        font-size: 15px;
    }

    #winner{
        font-size: 45px;
        color: antiquewhite;
    }
</style>
<body>

<div id="app"></div>
<script type="text/babel">

    class App extends React.Component {
        // 构造函数
        constructor(props) {
            super(props);
            this.state = {
                num1: 1,
                num2: 1,
                response: "",
                score: 0
            };
        }

        render() {
            if (this.state.score === 10) {
                return (
                    <div id="winner">You win!!!</div>
                );
            } else {
                return (
                    <div>
                        <div>{this.state.num1} + {this.state.num2}</div>
                        <input onKeyPress={this.inputKeyPress} onChange={this.updateResponse}
                               value={this.state.response}/>
                        <div>Score : {this.state.score}</div>
                    </div>
                );
            }
        }

        inputKeyPress = (event) => {
            if (event.key === "Enter") {
                const answer = parseInt(this.state.response);
                if (answer === this.state.num1 + this.state.num2) {
                    this.setState(state => ({
                        score: state.score + 1,
                        num1: Math.ceil(Math.random() * 10),
                        num2: Math.ceil(Math.random() * 10),
                        response: ""
                    }));
                } else {
                    this.setState(state => ({
                        score: state.score - 1
                    }));
                }
            }
        }

        updateResponse = (event) => {
            this.setState({
                response: event.target.value
            });
        }

    }

    ReactDOM.render(<App/>, document.querySelector('#app'));

</script>
</body>
</html>